<template>
  <ContentWrap>
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane name="config" label="发放配置">
        <RedPacketConfigForm v-hasRole="['shop_admin']" />
        <el-table
          v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
          :data="tableData.list"
          size="large"
          v-loading="tableData.loading"
        >
          <template #empty>
            <span>{{ !tableData.loading ? '没有相关数据' : '' }}</span>
          </template>
          <el-table-column
            v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
            label="所属店铺"
            min-width="150"
          >
            <template #default="{ row }">
              <div>{{ row.shop?.name || row.shopId }}</div>
            </template>
          </el-table-column>
          <el-table-column label="新客红包金额" min-width="120">
            <template #default="{ row }">
              <div
                >发放<b class="text-orange-500">{{ fenToYuan(row.firstAmount) }}元</b></div
              >
            </template>
          </el-table-column>
          <el-table-column label="消费红包金额" min-width="170">
            <template #default="{ row }">
              <div class="flex items-baseline">
                <b v-if="row.continueGrantScene === 1">扫码收款</b>
                <b v-else-if="row.continueGrantScene === 2">在线购物</b>
                <b v-else>扫码收款及在线购物</b>
                <b class="text-orange-500">满{{ fenToYuan(row.continueThresholdPrice) }}元</b>
                <span>后发放</span>
                <b class="text-orange-500">{{ fenToYuan(row.continueAmount) }}元</b>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="红包有效期" min-width="100">
            <template #default="{ row }">
              <div
                >发放后<b>{{ row.validationDays }}天内</b>有效
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开关" width="80">
            <template #default="{ row }">
              <el-tag :type="row.featureEnable ? 'success' : 'warning'">
                {{ row.featureEnable ? '开启' : '关闭' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
          />
        </el-table>
      </el-tab-pane>
      <el-tab-pane name="activity" label="抵扣规则">
        <el-button
          v-hasRole="['shop_admin']"
          type="primary"
          plain
          size="small"
          class="mt-2"
          @click="addActivity"
        >
          新增红包抵扣规则
        </el-button>
        <el-table
          :data="tableData.list"
          size="large"
          v-loading="tableData.loading"
          class="mt-[3px]"
        >
          <template #empty>
            <span>{{ !tableData.loading ? '没有相关数据' : '' }}</span>
          </template>
          <el-table-column
            v-hasRole="['super_admin', 'platform_admin', 'tenant_admin']"
            label="所属店铺"
            min-width="150"
          >
            <template #default="{ row }">
              <div>{{ row.shop?.name || row.shopId }}</div>
            </template>
          </el-table-column>
          <el-table-column label="类型" min-width="100">
            <template #default="{ row }">{{ row.typeName }}</template>
          </el-table-column>
          <el-table-column label="时间段" min-width="220">
            <template #default="{ row }"
              >{{ formatTime(row.startTime) }} ~
              {{ formatTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="门槛金额" min-width="120">
            <template #default="{ row }">{{ fenToYuan(row.thresholdPrice) }}元</template>
          </el-table-column>
          <el-table-column label="抵扣金额" min-width="120">
            <template #default="{ row }">{{ fenToYuan(row.discountPrice) }}元</template>
          </el-table-column>
          <el-table-column label="开关" width="80">
            <template #default="{ row }">
              <el-tag :type="row.enable ? 'success' : 'info'"
                >{{ row.enable ? '开启' : '关闭' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180"
          />
          <el-table-column v-hasRole="['shop_admin']" label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="editActivity(row)"
                >编辑
              </el-button>
              <el-button size="small" type="danger" link @click="removeActivity(row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <Pagination
      v-if="activeTab === 'activity'"
      v-model:limit="tableData.searchParam.pageSize"
      v-model:page="tableData.searchParam.pageNo"
      :total="tableData.total"
      @pagination="loadConfigData"
    />
    <RedPacketActivityForm
      ref="activityFormDialogRef"
      v-hasRole="['shop_admin']"
      @refresh="loadActivityData"
    />
  </ContentWrap>
</template>

<!--suppress HtmlUnknownAttribute -->
<script lang="ts" setup name="RedPacketConfigList">
import * as RedPacketConfigApi from '@/api/promotion/redpacket/RedPacketConfigApi'
import * as RedPacketActivityApi from '@/api/promotion/redpacket/RedPacketActivityApi'
import { dateFormatter, formatDate, formatTime } from '@/utils/formatTime'
import { fenToYuan } from '@/utils'
import { checkRole } from '@/utils/permission'
import { TabsPaneContext } from 'element-plus'
import RedPacketConfigForm from './RedPacketConfigForm.vue'
import RedPacketActivityForm from './RedPacketActivityForm.vue'

const tableData = reactive({
  total: 0,
  loading: true,
  list: [],
  searchParam: {
    pageNo: 1,
    pageSize: 10,
    createTime: []
  }
})

const activeTab = ref('config')

const handleTabClick = (tab: TabsPaneContext) => {
  console.debug('activeTab=', tab.paneName)
  activeTab.value = tab.paneName as string
  if (tab.paneName === 'activity') {
    loadActivityData()
  } else {
    loadConfigData()
  }
}

const loadActivityData = async () => {
  tableData.loading = true
  try {
    const res = await RedPacketActivityApi.getPage({
      ...tableData.searchParam
    })
    tableData.list = res.list
    tableData.total = res.total
  } finally {
    tableData.loading = false
  }
}
const loadConfigData = async () => {
  tableData.loading = true
  try {
    const res = await RedPacketConfigApi.getPage({
      ...tableData.searchParam
    })
    tableData.list = res.list
    tableData.total = res.total
  } finally {
    tableData.loading = false
  }
}

const activityFormDialogRef = ref()

const addActivity = () => {
  const ymd = formatDate(new Date(), 'YYYY-MM-DD')
  activityFormDialogRef.value?.openActivity({
    type: undefined,
    startTime: ymd + ' 00:00:00',
    endTime: ymd + ' 23:59:59',
    thresholdPrice: 0,
    discountPrice: 0,
    enable: true
  })
}
const editActivity = (row: any) => {
  activityFormDialogRef.value?.openActivity(row)
}
const removeActivity = (row: any) => {
  activityFormDialogRef.value?.deleteActivity(row)
}

onMounted(async () => {
  if (checkRole(['shop_admin'])) {
    await loadActivityData()
    return
  }
  tableData.searchParam.pageNo = 1
  await loadConfigData()
})
</script>
